package com.panghl.service;

import com.panghl.common.Constant;
import com.panghl.domain.ManagerInfo;
import com.panghl.domain.ResponseResult;
import com.panghl.domain.User;
import com.panghl.utils.JwtUtil;
import com.panghl.config.redis.RedisCache;
import com.panghl.utils.ShiroKit;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author panghl
 * @Date 2022/2/12
 * @Description 登录实现类
 **/
@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ManagerInfoService managerInfoService;

    @Override
    public ResponseResult login(User user) {
        String userName = user.getUserName();
        String password = user.getPassword();
        ManagerInfo managerInfo = managerInfoService.queryManagerInfoByUserName(userName);
        if (Objects.isNull(managerInfo)) {
            new RuntimeException("用户不存在！");
        }
        // 原密码加密（通过username + salt作为盐）
        String saltAfterPwd = ShiroKit.md5(password, userName + managerInfo.getUser().getSalt());
        if (managerInfo.getUser().getPassword().equalsIgnoreCase(saltAfterPwd)) {
            //创建token令牌并返回给前端
            Map<String,String> map = new HashMap<>();
            map.put("key",createToken(managerInfo));
            //httpServletResponse.setHeader("Authorization", token);
            //httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
            return new ResponseResult(200, "登录成功",map);
        }
        return new ResponseResult(-1, "账号或密码错误");
    }

    /**
     * 创建token令牌
     * @param managerInfo
     * @return
     */
    public String createToken(ManagerInfo managerInfo){
        String token = UUID.randomUUID().toString();
        String userKey = Constant.PREFIX_SHIRO_ACCESS_TOKEN+token;
        redisCache.setCacheObject(userKey,managerInfo, Math.toIntExact(JwtUtil.JWT_TTL), TimeUnit.MILLISECONDS);
        return JwtUtil.createJWT(token);
    }

    @Override
    public ResponseResult logout() {
        return new ResponseResult(200, "注销成功");
    }



    public static void main(String[] args) {
        String userName = "admin";
        String password = "123456";
        String salt = "PANGHL";
        String saltAfterPwd = ShiroKit.md5(password, userName + salt);
        System.out.println("加密后：" + saltAfterPwd);
    }

}
